package com.seven.aspect;

import com.seven.annotation.AuthAnnotation;
import com.seven.utils.JWTUtil;
import com.seven.vo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author longlong
 * @date 2024/3/7 14:36
 * description
 */
@Component
@Aspect
public class AuthAspect {
    @Autowired
    private HttpServletRequest request;

    //定义切面
    @Pointcut(value = "@annotation(com.seven.annotation.AuthAnnotation)")
    private void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        System.out.println("========sig"+signature);
        Method method = signature.getMethod();
        System.out.println("======="+method);
        AuthAnnotation annotation = method.getAnnotation(AuthAnnotation.class);
        System.out.println("========="+annotation);
        String value = annotation.value();
        System.out.println("========="+value);
        String token = request.getHeader("token");
        List<String> roles = JWTUtil.parseRoles(token);
        if (roles.contains(value)){
            Object proceed = point.proceed();
            return proceed;
        }
        Result result = new Result(4003, "权限不足", null);
        return result;
    }
}

